<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="sql查询性能优化,">










<meta name="description" content="本文详细讲解一下Pgsql中的EXPLAIN命令用法">
<meta name="keywords" content="sql查询性能优化">
<meta property="og:type" content="article">
<meta property="og:title" content="Pgsql中的EXPLAIN命令用法详解">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2020/01/10/how-to-use-explain-in-pgsql/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文详细讲解一下Pgsql中的EXPLAIN命令用法">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110095858901.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110134402541.jpg">
<meta property="og:updated_time" content="2020-01-10T06:09:24.509Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Pgsql中的EXPLAIN命令用法详解">
<meta name="twitter:description" content="本文详细讲解一下Pgsql中的EXPLAIN命令用法">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20200110095858901.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2020/01/10/how-to-use-explain-in-pgsql/">





  <title>Pgsql中的EXPLAIN命令用法详解 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2020/01/10/how-to-use-explain-in-pgsql/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Pgsql中的EXPLAIN命令用法详解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-10T05:50:40+08:00">
                2020-01-10
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/PostgreSQL/" itemprop="url" rel="index">
                    <span itemprop="name">PostgreSQL</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文详细讲解一下Pgsql中的EXPLAIN命令用法</p>
<a id="more"></a>

<blockquote>
<p>本文内容引用自：<a href="https://www.cnblogs.com/xueqiuqiu/articles/10999863.html" target="_blank" rel="noopener">https://www.cnblogs.com/xueqiuqiu/articles/10999863.html</a><br><a href="https://blog.csdn.net/kmblack1/article/details/80761647" target="_blank" rel="noopener">https://blog.csdn.net/kmblack1/article/details/80761647</a></p>
</blockquote>
<p>在使用数据库SQL时总会遇到执行慢的情况，虽然原因有很多，但是对于PostgreSQL DBA来说，好像有个共识，遇到用户慢SQL优化的问题，先拿EXPLAIN命令查看下对应的查询计划，从而可以快速定位SQL慢在哪里。</p>
<p>PostgreSQL官网中关于EXPLAIN的介绍: <a href="https://www.postgresql.org/docs/9.4/sql-explain.html" target="_blank" rel="noopener">https://www.postgresql.org/docs/9.4/sql-explain.html</a></p>
<h2 id="EXPLAIN-语法"><a href="#EXPLAIN-语法" class="headerlink" title="EXPLAIN 语法"></a>EXPLAIN 语法</h2><ol>
<li>在PostgreSQL中，EXPLAIN 命令可以输出SQL语句的查询计划，具体语法如下：<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">EXPLAIN</span> [ ( <span class="keyword">option</span> [, ...] ) ] <span class="keyword">sql</span>查询语句</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>其中option参数可以是下面的一个或多个<br><img src="/blog/images/20200110095858901.jpg" alt="option参数"></p>
<p>EXPLAIN 的使用示例如下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">EXPLAIN</span> (<span class="keyword">analyze</span>,buffers,verbose) <span class="keyword">select</span> <span class="keyword">name</span> <span class="keyword">from</span> <span class="keyword">test</span> <span class="keyword">where</span> <span class="keyword">id</span> <span class="keyword">like</span> <span class="string">'%93%'</span></span><br></pre></td></tr></table></figure>

<ol start="2">
<li>EXPLAIN 命令中各option参数的含义见下表：</li>
</ol>
<table>
<thead>
<tr>
<th>参数</th>
<th>含义</th>
<th>数据类型与默认值</th>
</tr>
</thead>
<tbody><tr>
<td>ANALYZE</td>
<td>获得相应的查询计划。注意:ANALYZE为TRUE时会真正执行SQL语句</td>
<td>boolean, false</td>
</tr>
<tr>
<td>VERBOSE</td>
<td>为TRUE时显示查询计划的附加信息,包括查询计划中每个节点（后面具体解释节点的含义）输出的列（Output），表的SCHEMA 信息，函数的SCHEMA 信息，表达式中列所属表的别名，被触发的触发器名称等</td>
<td>boolean, false</td>
</tr>
<tr>
<td>COSTS</td>
<td>为TRUE时显示每个计划节点的预估启动代价（找到第一个符合条件的结果的代价）和总代价，以及预估行数和每行宽度</td>
<td>boolean, true</td>
</tr>
<tr>
<td>BUFFERS</td>
<td>为TRUE时显示关于缓存的使用信息。该参数只能与ANALYZE 参数一起使用。缓冲区信息包括共享块（常规表或者索引块）、本地块（临时表或者索引块）和临时块（排序或者哈希等涉及到的短期存在的数据块）的命中块数，更新块数，挤出块数。</td>
<td>boolean, false</td>
</tr>
<tr>
<td>TIMING</td>
<td>为TRUE会显示每个计划节点的实际启动时间和总的执行时间。该参数只能与ANALYZE 参数一起使用。因为对于一些系统来说，获取系统时间需要比较大的代价，如果只需要准确的返回行数，而不需要准确的时间，可以把该参数关闭。</td>
<td>boolean, true</td>
</tr>
<tr>
<td>FORMAT</td>
<td>指定输出格式。 默认为各个格式输出的内容都是相同的，其中XML、 JSON、YAML 更有利于通过程序解析SQL 语句的查询计划</td>
<td>TEXT</td>
</tr>
</tbody></table>
<h2 id="EXPLAIN命令用法详解"><a href="#EXPLAIN命令用法详解" class="headerlink" title="EXPLAIN命令用法详解"></a>EXPLAIN命令用法详解</h2><blockquote>
<p>以下内容转载自：《详解 PostgreSQL explain 查询计划》 <a href="https://blog.csdn.net/kmblack1/article/details/80761647" target="_blank" rel="noopener">https://blog.csdn.net/kmblack1/article/details/80761647</a></p>
</blockquote>
<p><strong>•除第一行以外每个-&gt;表示一个子动作<br>•执行计划的阅读顺序都是从后至前<br>•width=0是表示只获取行的位置,没有读取数据.开始读数据后width肯定大于0</strong></p>
<blockquote>
<p>EXPLAIN用于理解和优化SQL查询,它接受SELECT …,UPDATE …或DELETE …之类的sql命令并返回查询计划，查询计划详细说明了执行sql所采取的方法.</p>
</blockquote>
<blockquote>
<p>以下结合实例讲解一个执行计划:</p>
</blockquote>
<p>SQL实例代码如下：</p>
<figure class="highlight mipsasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">EXPLAIN ANALYZE SELECT *</span><br><span class="line">FROM tenk1 <span class="built_in">t1</span>, tenk2 <span class="built_in">t2</span></span><br><span class="line">WHERE <span class="built_in">t1</span>.unique1 &lt; <span class="number">100</span> <span class="keyword">AND </span><span class="built_in">t1</span>.unique2 = <span class="built_in">t2</span>.unique2 <span class="keyword">ORDER </span><span class="keyword">BY </span><span class="built_in">t1</span>.fivethous<span class="comment">;</span></span><br></pre></td></tr></table></figure>

<p>执行计划的结果如下：<br><img src="/blog/images/20200110134402541.jpg" alt="执行计划"></p>
<p>PostgreSQL建立了一个计划节点的树状结构,代表所采取的不同动作,除第一行以外每个-&gt;表示一个子动作,因此上图的查询结构为:</p>
<figure class="highlight mathematica"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">Sort</span></span><br><span class="line">└── <span class="keyword">Hash</span> <span class="keyword">Join</span></span><br><span class="line">    ├── Seq <span class="keyword">Scan</span></span><br><span class="line">    └── <span class="keyword">Hash</span></span><br><span class="line">        └── Bitmap Heap <span class="keyword">Scan</span></span><br><span class="line">            └── Bitmap Index <span class="keyword">Scan</span></span><br></pre></td></tr></table></figure>

<p>每个节点表示子动作,<strong>阅读顺序从后至前</strong>。因此上面的执行计划第一步是在tenk_unique1索引上进行Bitmap Index Scan.</p>
<h3 id="Step-1"><a href="#Step-1" class="headerlink" title="Step 1"></a>Step 1</h3><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Bitmap Index Scan on tenk1_unique1  (<span class="attribute">cost</span>=0.00..5.04 <span class="attribute">rows</span>=101 <span class="attribute">width</span>=0) (actual <span class="attribute">time</span>=0.049..0.049 <span class="attribute">rows</span>=100 <span class="attribute">loops</span>=1)</span><br><span class="line">      Index Cond: (unique1 &lt; 100)</span><br></pre></td></tr></table></figure>

<p>上述代码的含义是：</p>
<ol>
<li>本步骤对应于SQL中的”WHERE t1.unique1&lt;100”。PostgreSQL匹配索引条件”unique1&lt;100”的行,行本身不会在这里返回(width=0).</li>
<li>成本(cost)估算(cost=0.00..5.04 rows=101 width=0)中的”cost=0.00..5.04”意味着PostgreSQL希望花费”5.04”的任意计算单位来找到这些值,”0.00”是该节点起始工作成本(只是启动成本).”rows=101”是此索引扫描将返回的估计行数.width是返回行的估计大小(以字节为单位),”width=0”是因为此处只获取数据的实际位置(ctid)而不是返回行的内容.</li>
<li>因为使用ANALYZE选项运行EXPLAIN,所以查询实际上已执行并且捕获了时间信息.”(actual time=0.049..0.049 rows=100 loops=1)”,”loops=1”表示索引扫描被执行了1次;”rows=100”表示返回了100行;”actual time=0.049..0.049”表示此步骤的开始时间是0.049,结束时间0.049,单位为毫秒,因此此实际执行时间是0,实际时间是每次迭代的平均值,可以将值乘以循环次数以获得真实的执行时间.</li>
<li>成本或时间范围值可能不同,因此给出了最小/最大时间的概念,上例中查询的每单位成本比率为 “0.049ms/5.04成本单位≈0.01ms/每个成本单位”,注意是actual time的结束时间/cost结束成本。</li>
</ol>
<h3 id="Step-2"><a href="#Step-2" class="headerlink" title="Step 2"></a>Step 2</h3><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Bitmap Heap Scan on tenk1 t1  (<span class="attribute">cost</span>=5.07..229.20 <span class="attribute">rows</span>=101 <span class="attribute">width</span>=244) (actual <span class="attribute">time</span>=0.080..0.526 <span class="attribute">rows</span>=100 <span class="attribute">loops</span>=1)</span><br><span class="line">      Recheck Cond: (unique1 &lt; 100)</span><br></pre></td></tr></table></figure>

<p>上述代码的含义是：</p>
<ol>
<li>将Step 1索引扫描的结果传递给”Bitmap Heap Scan”操作。在这个节点中,PostgreSQL取得tenk1表(别名为t1)中行的位置,”unique1 &lt; 100”从表中取出行.</li>
<li>可以看到成本预期乘以Step 1计算的值0.01,意味着大概的预期时间(229.20-5.07) * 0.01≈2.24ms ,但是实际时间为0.526ms每行,实际时间是大概的预期时间1/4,这可能是因为成本估算值是一个上限值,并非所有行都需要读取,或者因为重新检查条件始终为真。</li>
<li>Bitmap Index Scan和Bitmap Heap Scan的组合比从表中顺序读取行(Seq Scan)要昂贵得多,但由于在这种情况下需要访问的行相对较少,所以速度更快.</li>
<li>通过在提取这些行之前将这些行排序为物理顺序可以进一步提高速度,从而最大限度地降低单独提取的成本.</li>
</ol>
<h3 id="Step-3"><a href="#Step-3" class="headerlink" title="Step 3"></a>Step 3</h3><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Hash  (<span class="attribute">cost</span>=229.20..229.20 <span class="attribute">rows</span>=101 <span class="attribute">width</span>=244) (actual <span class="attribute">time</span>=0.659..0.659 <span class="attribute">rows</span>=100 <span class="attribute">loops</span>=1)</span><br><span class="line">      Buckets: 1024  Batches: 1  Memory Usage: 28kB</span><br></pre></td></tr></table></figure>

<ol>
<li>堆扫描Step 2(Heap Scan)的结果中,来自表tenk1且”unique1&lt;100”的行会在读取时插入到内存哈希表中,正如我们从成本上看到的那样,这个步骤完全没有占用运行时间(cost=229.20..229.20)(actual time=0.659..0.659)。</li>
<li>Hash包含Buckets和Batches以及内存使用情况的信息.如果Batches&gt;1,则还涉及磁盘使用情况,本例中无.内存使用情况通过公式大约为”100x244=24.4kB”,接近实际使用的内存28kB,多出来的部分假设为Hash密钥本身所占用的内存.</li>
</ol>
<h3 id="Step-4"><a href="#Step-4" class="headerlink" title="Step 4"></a>Step 4</h3><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Hash Join  (<span class="attribute">cost</span>=230.47..713.98 <span class="attribute">rows</span>=101 <span class="attribute">width</span>=488) (actual <span class="attribute">time</span>=0.711..7.427 <span class="attribute">rows</span>=100 <span class="attribute">loops</span>=1)</span><br><span class="line">      Hash Cond: (t2.unique2 = t1.unique2)</span><br><span class="line">      -&gt;  Seq Scan on tenk2 t2  (<span class="attribute">cost</span>=0.00..445.00 <span class="attribute">rows</span>=10000 <span class="attribute">width</span>=244) (actual <span class="attribute">time</span>=0.007..2.583 <span class="attribute">rows</span>=10000 <span class="attribute">loops</span>=1)</span><br></pre></td></tr></table></figure>

<ol>
<li>PostgreSQL从tenk2中读取所有10000行(别名为t2),并根据tenk1的Hash来检查它们.Hash Join意味着一个表的行被输入到内存中的Hash,之后扫描另一个表的行,并根据Hash探测匹配的值,在第二行为匹配条件”Hash Cond: (t2.unique2 = t1.unique2)”.</li>
<li>请注意,因为查询选择了tenk1和tenk2中的所有值,所以在哈希连接期间每行的宽度都会增加一倍。</li>
<li>注意观察,在本示例中执行时间大部份花在这上步骤上(actual time=0.711..7.427).Step 4花费了7.427ms,占总执行时间的7.427/7.774=95%.</li>
</ol>
<h3 id="Step-5"><a href="#Step-5" class="headerlink" title="Step 5"></a>Step 5</h3><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Sort  (<span class="attribute">cost</span>=717.34..717.59 <span class="attribute">rows</span>=101 <span class="attribute">width</span>=488) (actual <span class="attribute">time</span>=7.761..7.774 <span class="attribute">rows</span>=100 <span class="attribute">loops</span>=1)</span><br><span class="line">  Sort Key: t1.fivethous</span><br><span class="line">  Sort Method: quicksort  Memory: 77kB</span><br><span class="line">Planning time: 0.194 ms</span><br><span class="line">Execution time: 8.008 ms</span><br></pre></td></tr></table></figure>

<ol>
<li>所有符合条件的行都已经收集完毕,然后通过Sort Key: t1.fivethous排序结果集.</li>
<li>排序的算法为quicksort,Memory表示排序是在内存上完成的,使用了77kB大小的内存.当排序所需的内存超过work_mem参数的大小时,将使用磁盘空间,这将极大影响查询速度</li>
<li>排序使用磁盘空间时需要增加work_mem大小,以避免使用磁盘空间</li>
<li>注意排序是在内存和磁盘上完成的,优先使用内存,因此实际所需空间大小=所需的内存/所需的磁盘空间</li>
<li>这个查询所需要的时间大约为7.774ms,符合Execution time: 8.008 ms的时间</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/sql查询性能优化/" rel="tag"># sql查询性能优化</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2020/01/09/how-to-install-pgsql-on-centos6.8/" rel="next" title="CentOS6.8下安装pgsql19.6">
                <i class="fa fa-chevron-left"></i> CentOS6.8下安装pgsql19.6
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2020/01/10/how-to-use-coalesce-in-pgsql/" rel="prev" title="Pgsql中的常用函数用法详解">
                Pgsql中的常用函数用法详解 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#EXPLAIN-语法"><span class="nav-number">1.</span> <span class="nav-text">EXPLAIN 语法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#EXPLAIN命令用法详解"><span class="nav-number">2.</span> <span class="nav-text">EXPLAIN命令用法详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Step-1"><span class="nav-number">2.1.</span> <span class="nav-text">Step 1</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Step-2"><span class="nav-number">2.2.</span> <span class="nav-text">Step 2</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Step-3"><span class="nav-number">2.3.</span> <span class="nav-text">Step 3</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Step-4"><span class="nav-number">2.4.</span> <span class="nav-text">Step 4</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Step-5"><span class="nav-number">2.5.</span> <span class="nav-text">Step 5</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
